// ======================================================================
// Copyright (C) 2013 Hell-Prototypes. / www.hellprototypes.com
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// ======================================================================
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    14:41:22 05/02/2013 
// Design Name: 
// Module Name:    LB1848M 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module A3967SLB(
    input CLK,
    input nRST,

    input [12:0] Step_Num,
    input direction,
    input launch,
	input step_ctrl,
	
	input edge_far,
	input edge_near,
	
	output reg EN,
    output DIR,
    output reg STEP
    );

reg [12:0]step_counter, next_step_counter;
reg dir_latch, next_dir_latch;
reg next_STEP;
reg next_EN;
//reg [3:0] ACC_DEC_ctrl, next_ACC_DEC_ctrl;
//reg [3:0] ACC_DEC_count, next_ACC_DEC_count;
wire clear_step_counter;

assign DIR = dir_latch;
assign clear_step_counter = (|step_counter) & ( (DIR & (~edge_far)) | ((~DIR) & (~edge_near)) );

always @(posedge CLK or negedge nRST) begin
	if(!nRST) begin
		step_counter <=0;
		dir_latch <= 0;

		EN <= 0;
		STEP <= 0;
	end else begin
		step_counter <= next_step_counter;
		dir_latch <= next_dir_latch;

		EN <= next_EN;
		STEP <= next_STEP;
	end
end

always @* begin
	next_step_counter = step_counter;
	next_dir_latch = dir_latch;
	next_EN = EN;
	next_STEP = STEP;

	if(launch) begin
		next_step_counter = Step_Num;
		next_dir_latch = direction;
		next_EN = 1;
	end else if(clear_step_counter) begin
		next_step_counter = 0;
	end else if(step_ctrl) begin
		if(!STEP) begin
			if(|step_counter) begin
				next_step_counter = step_counter - 1;
				next_STEP = 1;
			end else begin
				next_EN = 0;
			end
		end else begin
			next_STEP = 0;
		end
	end
end

endmodule
